using System;
using System.Threading;

namespace Conusic
{
    /// <summary>
    /// special mutex to allow no more 1 enter per timeout 
    /// </summary>
    public class ThreadTube
    {
        private int timeout;
        private DateTime lastAccess = new DateTime(1);
        private const int TicksToMillisecond = 10000;

        private Mutex safeMutex = new Mutex();

        public ThreadTube(int timeout)
        {
            this.timeout = timeout;
        }

        public void Wait()
        {
            //enter to thread safe section
            safeMutex.WaitOne();

            DateTime current = DateTime.Now;
            if (current.Ticks - lastAccess.Ticks < timeout*TicksToMillisecond)
            {
                int delay = timeout - (int) (current.Ticks - lastAccess.Ticks)/TicksToMillisecond;
                Thread.Sleep(delay);
            }
            lastAccess = DateTime.Now;

            //exit from thread safe section
            safeMutex.ReleaseMutex();
        }
    }
}